package taillog

import (
    "LogAgent/etcd"
    "fmt"
)

var (
    tailMgr  *TailMgr
    TaskMap = map[string]*TailTask{}
)

type TailMgr struct {
    logEntrys []*etcd.LogEntry
}

func Init(logEntrys []*etcd.LogEntry){
     tailMgr=&TailMgr{
         logEntrys: logEntrys,
     }

    for _, logEntry := range logEntrys {
        //初始化tailTask并放入到map中
        tailTask := NewTailTask(logEntry.Topic, logEntry.Path)
        TaskMap[logEntry.Topic]=tailTask
    }

}

func WatchConfig(key string) {
    rch:=etcd.WatchLogEntryConf(key)
    for _ = range rch {
        //说明监听的key发生了变化，则再次读取配置
        logEntrys, _ := etcd.GetLogEntryConf(key)

        //增加任务
        for _, entry := range logEntrys {
            //如果包含则跳过
            if  _,ok:=TaskMap[entry.Topic];ok{
                continue
            }
            //增加任务
            fmt.Printf("create a new task for topic %s\n",entry.Topic)
            newTask := NewTailTask(entry.Topic, entry.Path)
            TaskMap[entry.Topic]=newTask
        }

        deleteTopicList:=[]string{}
        for key := range TaskMap {
            isIn:=false
            for _, entry := range logEntrys {

                if key == entry.Topic {
                    isIn=true
                }

            }
            if !isIn{
                deleteTopicList=append(deleteTopicList,key)
            }
        }

        //删除任务
        for _, topic := range deleteTopicList {
            task := TaskMap[topic]
            fmt.Println("delete task ,the task's topoic is ",topic)
            task.cancel()
            delete(TaskMap,topic)
        }

    }
}
